/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.fty.web;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import com.jeesite.common.cache.CacheUtils;
import com.jeesite.common.entity.DataScope;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.modules.BeanMapUtil;
import com.jeesite.modules.ChinaFontProvide;
import com.jeesite.modules.ChinaFontProvide1;
import com.jeesite.modules.Watermark;
import com.jeesite.modules.fty.entity.FtyLeaseContractFull;
import com.jeesite.modules.fty.entity.FtySelContract;
import com.jeesite.modules.fty.service.FtyLeaseContractFullService;
import com.jeesite.modules.fty.service.FtySelContractService;
import com.jeesite.modules.sys.entity.DictData;
import com.jeesite.modules.sys.entity.UserDataScope;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.poifs.nio.DataSource;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.fty.entity.FtyLeaseContractSmart;
import com.jeesite.modules.fty.service.FtyLeaseContractSmartService;

import java.beans.IntrospectionException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 合同表Controller
 * @author 租凭合同简单版本
 * @version 2018-04-23
 */
@Controller
@RequestMapping(value = "${adminPath}/fty/ftyLeaseContractSmart")
public class FtyLeaseContractSmartController extends BaseController {

	@Autowired
	private FtyLeaseContractSmartService ftyLeaseContractSmartService;
	

	/**
	 * 查询列表数据
	 */
	@Resource
	FtySelContractService ftySelContractService;
	@Resource
	FtyLeaseContractFullService ftyLeaseContractFullService;


	/**
	 * 获取数据
	 */
	@ModelAttribute
	public FtyLeaseContractSmart get(String contractCode, boolean isNewRecord) {
		return ftyLeaseContractSmartService.get(contractCode, isNewRecord);
	}





	/**
	 * 查询列表
	 */
	@RequiresPermissions("fty:ftyLeaseContractSmart:view")
	@RequestMapping(value = {"list", ""})
	public String list(FtyLeaseContractSmart ftyLeaseContractSmart, Model model) {
		model.addAttribute("ftyLeaseContractSmart", ftyLeaseContractSmart);
		return "modules/fty/ftyLeaseContractSmartList";
	}


	@RequestMapping(value = "countAll")
	@ResponseBody
	public long countAll (HttpServletRequest request, HttpServletResponse response) {
		FtyLeaseContractSmart ftyLeaseContractSmart = new FtyLeaseContractSmart();
		ftyLeaseContractSmart.getSqlMap().getWhere().and("c_number", QueryType.IS_NOT_NULL, null);
		if(! UserUtils.getUser().getUserCode().equals("admin")) {
			ftyLeaseContractSmart.getSqlMap().getDataScope().addFilter("dsfOffice", "Office", "e.office_code", "1");
		}

		long all= ftyLeaseContractSmartService.findCount(ftyLeaseContractSmart);
		FtyLeaseContractFull ftyLeaseContractFull = new FtyLeaseContractFull();
		if(! UserUtils.getUser().getUserCode().equals("admin")) {
			ftyLeaseContractFull.getSqlMap().getDataScope().addFilter("dsfOffice", "Office", "e.office_code", "1");

		}

		ftyLeaseContractFull.getSqlMap().getWhere().and("c_number", QueryType.IS_NOT_NULL, null);
		all += ftyLeaseContractFullService.findCount(ftyLeaseContractFull);

		FtySelContract ftySelContract = new FtySelContract();
		if(! UserUtils.getUser().getUserCode().equals("admin")) {
			ftySelContract.getSqlMap().getDataScope().addFilter("dsfOffice", "Office", "e.office_code", "1");
		}

		ftySelContract.getSqlMap().getWhere().and("c_number", QueryType.IS_NOT_NULL, null);
		all += ftySelContractService.findCount(ftySelContract);
		return all;
	}

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("fty:ftyLeaseContractSmart:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<FtyLeaseContractSmart> listData(FtyLeaseContractSmart ftyLeaseContractSmart, HttpServletRequest request, HttpServletResponse response) {

		ftyLeaseContractSmartService.addDataScopeFilter(ftyLeaseContractSmart, null);
		if( UserUtils.getUser().getUserCode().equals("admin")){
			ftyLeaseContractSmart.getSqlMap().getWhere().and("c_number", QueryType.IS_NOT_NULL, null);
		}else{

		}
		Page<FtyLeaseContractSmart> page = ftyLeaseContractSmartService.findPage(new Page<FtyLeaseContractSmart>(request, response), ftyLeaseContractSmart);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("fty:ftyLeaseContractSmart:view")
	@RequestMapping(value = "form")
	public String form(FtyLeaseContractSmart ftyLeaseContractSmart, Model model) {
		model.addAttribute("ftyLeaseContractSmart", ftyLeaseContractSmart);
		return "modules/fty/ftyLeaseContractSmartForm";
	}



	@RequestMapping(value = {"generalNumber"})
	@ResponseBody
	public String generalNumber(FtyLeaseContractSmart ftyLeaseContractSmart, Model model) {
		if(!ftyLeaseContractSmart.getCreateBy().equals(EmpUtils.getEmployee().getEmpCode()))
			return renderResult(Global.FALSE, "您不是合同原件创建人,无法生成合同");
		if(StringUtils.isNotBlank(ftyLeaseContractSmart.getCNumber()))
			return renderResult(Global.FALSE, "有序列号的合同已经生成,无法改变");
		ftyLeaseContractSmartService.generalUUid(ftyLeaseContractSmart);
		return renderResult(Global.TRUE, "生成合同编号成功！");
	}


	/**
	 * 保存合同表
	 */
	@RequiresPermissions("fty:ftyLeaseContractSmart:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated FtyLeaseContractSmart ftyLeaseContractSmart) {
		if(ftyLeaseContractSmart!=null) {
			if (ftyLeaseContractSmart.getCreateBy()!=null&&!EmpUtils.getEmployee().getEmpCode().equals(ftyLeaseContractSmart.getCreateBy()))
				return renderResult(Global.FALSE, "您不是合同原件创建人,无法操作合同");
		}
		ftyLeaseContractSmart.setCName(EmpUtils.getCompany().getFullName());
		ftyLeaseContractSmartService.save(ftyLeaseContractSmart);
		return renderResult(Global.TRUE, "保存合同表成功！");
	}
	
	/**
	 * 删除合同表
	 */
	@RequiresPermissions("fty:ftyLeaseContractSmart:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(FtyLeaseContractSmart ftyLeaseContractSmart) {
		ftyLeaseContractSmartService.delete(ftyLeaseContractSmart);
		return renderResult(Global.TRUE, "删除合同表成功！");
	}
	@RequestMapping("/contract")
	public void sellercontract(FtyLeaseContractSmart ftyLeaseContractSmart, HttpServletRequest request,
							   HttpServletResponse response, HttpSession session)
			throws Exception{
		Map<String, Object> map = BeanMapUtil.bean2Map(ftyLeaseContractSmart);

		response.setContentType("application/pdf");
		response.setHeader("Expires", "0");// 不缓存
		response.setHeader("Cache-Control",
				"must-revalidate, post-check=0, pre-check=0");
		response.setHeader("Pragma", "public");

		String contract = Global.getConfig("sys.leasecontract.easy", "10");
		BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",
				"UniGB-UCS2-H", false);
		Font fontBold = new Font(bfChinese, 25, Font.NORMAL);
		InputStream cssStream = request.getServletContext().getResourceAsStream("/static/fang/style/word.css");
		//要替换的字符名称
		String lender = "";

			Document document = new Document();
			ServletOutputStream out = response.getOutputStream();
			PdfWriter writer = PdfWriter.getInstance(document, out);// 输出到浏览器
			writer.setPageEvent(new Watermark(ftyLeaseContractSmart.getCNumber()));//水印内容 添加事件 在事件中添加水印

			document.addTitle("房屋租赁中介合同");// 仅仅是文档属性里的标题，不显示在页面
			document.open();
			//文字水印
			//添加水印和页码
//			Paragraph title = new Paragraph("房屋租凭中介合同", fontBold);
//			title.setAlignment(Element.ALIGN_CENTER);
//			document.add(title);
			String contract1 = null;
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

				for (Map.Entry<String, Object> entry : map.entrySet()) {
					String key = entry.getKey().toLowerCase();
					Object value = entry.getValue();
					if(entry.getValue() instanceof Date){
						value = formatter.format(value);
					}
					contract  = contract.replaceAll("\\#"+key+"\\#", String.valueOf(value)==null?"/":String.valueOf(value));

				}

			contract = contract.replaceAll("\\#c_name_full\\#", ftyLeaseContractSmart.getCName());
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
			contract = contract.replaceAll("\\#c_date\\#",format.format(ftyLeaseContractSmart.getCreateDate()) );


			ByteArrayInputStream bin = new ByteArrayInputStream(contract.getBytes());
			XMLWorkerHelper.getInstance().parseXHtml(writer,document, bin,  cssStream, new ChinaFontProvide());
			document.close();
			out.close();

	}
}